using System.Collections.Generic;
using Kotonoha.Server.Dictionaries;
using Kotonoha.Server.Examples;
using NHibernate;
using System.Linq;
using NHibernate.Linq;

namespace Kotonoha.Server.Db.Dao {
    public class DictDao : DaoBase {
        public DictDao(ISession session) : base(session) {}

        public CharEntry findChar(string ch) {
            return session.Linq<CharEntry>().Where(c => c.Writing == ch).First();
        }

        public IList<WordEntry> findWordByWriting(string writing) {
            IQuery query = session.CreateQuery("from WordEntry w join w.Writings wr where wr = :val");
            query.SetString("val", writing);
            return query.List<WordEntry>();
        }

        public IList<ExampleEntry> findExamples(string word, int max) {
            IQuery q =
                session.CreateQuery(
                "select i from ExampleInfo i join i.Word w " +
                "join w.Writings wr join fetch i.Example ee where wr = :val and length(ee.Content) < 50 order by i.Recommended desc");
            q.SetString("val", word);
            q.SetMaxResults(100);
            var enumerable = q.List<ExampleInfo>()
                .OrderBy(en => en.Recommended)
                .GroupBy(en => en.Number)
                .Select(g => g.Take(max))
                .SelectMany(g => g)
                .Select(i => i.Example);
            return enumerable.ToList();
        }
    }
}